import { Component,Input ,forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl} from "@angular/forms"
@Component({
  selector: 'app-image-list-select',
  templateUrl: './image-list-select.component.html',
  styleUrls: ['./image-list-select.component.scss'],
  providers:[
    {
      provide:NG_VALUE_ACCESSOR,//forwardRef 向前引用，他会等到我这边实例化以后，才会进行这个引用，但是并不妨碍我们把它放在里面，用useExising把他注册到依赖池里
      useExisting:forwardRef(()=>ImageListSelectComponent),//把自己注册到这个令牌上去
      multi:true//像这种令牌都是多对一，对应多个类
    },
    {
      provide:NG_VALIDATORS,
      useExisting:forwardRef(()=>ImageListSelectComponent),
      multi:true
    }
  ]
})
export class ImageListSelectComponent implements ControlValueAccessor {
  @Input() cols = 6;
  @Input() title = "选择";
  @Input() rowHeight = '64px';
  @Input() items:string[] = [];
  @Input() useSvgIcon:boolean = false;
  @Input() itemWidth ='80px';
  selected:string;
  constructor() { }
  private propagateChange = (_:any)=>{};
  onChange(i){
    this.selected = this.items[i];
    this.propagateChange(this.selected);
  }
  writeValue(obj: any): void{
    this.selected = obj;
  }
  registerOnChange(fn: any): void{
    this.propagateChange = fn;
  }
  registerOnTouched(fn: any): void{

  }
  validate(c:FormControl):{[key:string]:any}{
    return this.selected?null:{imageInvalid:{valid:false}}
  }
}
